#!/bin/bash
if [[ $env == 'dev' && $CI_BUILD_REF_NAME == 'develop'  || $CI_BUILD_REF_NAME =~ [mars|hotfix/][0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
   argv=(10.129.37.83)
elif [[ $env == 'uat' ]] && [[ $CI_BUILD_REF_NAME == 'uat' || $CI_BUILD_REF_NAME =~ [mars|hotfix/][0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
   argv=(10.129.37.106 10.129.37.107)
elif [[ $env == 'prod' ]] && [[ $CI_BUILD_REF_NAME == 'master' || $CI_BUILD_REF_NAME =~ [mars][0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
   argv=(10.129.2.10 10.129.2.11 10.129.2.12)
else
   echo 'Please enter env parameter 【dev|uat|prod】'
   exit 1
fi
#echo ${argv[@]}
#遍历IP并部署：部署先将gitlab编译的包放到机器的/tmp目录下，然后登录目标机器将包放到部署目录，并删除/tmp下内容。
pro_ip=""
deploy=0
count=0
for i in "${argv[@]}";do
	if [[ $count -eq 0 ]]; then
		deploy=1
	else
		k=0
		while [ $k -le 40 ]
		do
		 	return=`curl -o /dev/null -s -w %{http_code} http://${pro_ip}:9000/healthCheck`
		 	if [ ${return} -eq 200 ];then
		 		deploy=1
		 		echo "deploy $deploy"
		 		break		 		
			else
				let k++
				sleep 3
			fi
		done				
	fi    
	
	if [[ $deploy -eq 1 ]]; then
			scp -o stricthostkeychecking=no $CI_PROJECT_DIR/publish/* cifiadmin@$i:/tmp/ && \
		    ssh -o PasswordAuthentication=no -o StrictHostKeyChecking=no cifiadmin@$i "
		    source /etc/profile ;
		    ps aux |grep 'java'|grep 'cifi-mars-server'|grep -v 'grep' ;
		    \cp /tmp/cifi-mars-server.jar /app/mars/ ;
		    \cd /app/mars;
			/app/mars/stop.sh || exit 1 ;
			/app/mars/start.sh || exit 1 ;
		    rm -f /tmp/cifi-mars-server.jar ; 
		    ps aux |grep 'java'|grep 'cifi-mars-server'| grep -v 'grep' ;
		    exit 0 ;" || exit 1
		    echo " $i success"
		    pro_ip=$i
		    let count++
	else
			echo "$pro_ip 启动失败，请检查"
			exit 1
	fi
	deploy=0	
done
echo 'deploy successful!'
